package com.apex.memotouch.utils;

/**
 * <p>Copyright © 2016年 珠海艾派克科技股份有限公司. All rights reserved.
 */

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;

public class NfcConfigure {
	private NfcAdapter mNfcAdapter = null;
	private IntentFilter[] mFilters = null;
	private PendingIntent mPendingIntent = null;
	private String[][] mTechLists = null;
	protected Activity mActivity;

	public enum NFCCheck{
		UNSUPPORT,CLOSED,ENABLE
	}

	/**
	 * initial Activity NFC function
	 *
	 * @param activity
	 */
	public NfcConfigure(Activity activity) {
		this.mActivity = activity;
		initNfc();
	}

	/**
	 * 初始化NFC，创建一个前台调度的过滤器
	 *
	 * @author Jack
	 */
	protected void initNfc() {
		mPendingIntent = PendingIntent.getActivity(mActivity, 0, new Intent(
				mActivity, mActivity.getClass())
				.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		// FLAG_ACTIVITY_SINGLE_TOP: not creating multiple instances of the same
		// application.
		IntentFilter tagDetected = new IntentFilter(
				NfcAdapter.ACTION_TAG_DISCOVERED);
		IntentFilter ndefDetected = new IntentFilter(
				NfcAdapter.ACTION_NDEF_DISCOVERED);
		IntentFilter techDetected = new IntentFilter(
				NfcAdapter.ACTION_TECH_DISCOVERED);
		// ndef.addDataScheme("http");
		// Intent filters for writing to a tag
		mFilters = new IntentFilter[] { tagDetected, ndefDetected, techDetected };
		mTechLists = new String[][] { new String[] { Ndef.class.getName() },
				new String[] { NdefFormatable.class.getName() } };
	}

	/**
	 * Enable foreground dispatch to the given Activity
	 *
	 * @author Jack
	 */
	public void enableForegroundDispatch() {
		if (mNfcAdapter != null) {
			mNfcAdapter.enableForegroundDispatch(mActivity, mPendingIntent,
					mFilters, mTechLists);
		}
	}

	/**
	 * Disable foreground dispatch to the given activity.
	 *
	 * @author Jack
	 */
	public void disableForegroundDispatch() {
		if (mNfcAdapter != null) {
			mNfcAdapter.enableForegroundDispatch(mActivity, mPendingIntent,
					mFilters, mTechLists);
		}
	}


	/**
	 * 检查NFC功能，如果手机不支持NFC 返回false, 没打开NFC功能弹出相应的提示
	 *
	 * @author Simon
	 */
	public NFCCheck checkNfcFunction() {
		mNfcAdapter = NfcAdapter.getDefaultAdapter(mActivity);
		/** 手机不支持NFC功能 **/
		if (mNfcAdapter == null) {
			return NFCCheck.UNSUPPORT;
		} else {
			/** 手机支持NFC功能，但未开启 **/
			if (!mNfcAdapter.isEnabled()) {
				return NFCCheck.CLOSED;
			}
			return NFCCheck.ENABLE;
		}
	}
}
